import { Module } from 'vuex'
import { IRootState } from '../type'
import { ILoginState } from './type'

import localCache from '@/utils/localCache'

import { accountLoginRequest, requestUserInfoById, requestUserMenusByRoleId } from '@/service/login'
import router from '@/router'
import { mapMenusToRoutes, mapMenusToBtnPermission } from '@/utils/mapRoutes'

const LoginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      roleMenus: [],
      userMenus: [],
      btnPermission: []
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeRoleMenus(state, roleMenus: any[]) {
      state.roleMenus = roleMenus

      const routes = mapMenusToRoutes(roleMenus)

      console.log('routes', routes)

      routes.forEach(route => {
        router.addRoute('main', route)
      })

      // 获取用户的所有操作权限
      const btnPermission = mapMenusToBtnPermission(roleMenus)
      state.btnPermission = btnPermission
    }
  },
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: any) {
      // 登录逻辑
      const res = await accountLoginRequest(payload)
      const { id, token } = res.data
      commit('changeToken', token)
      localCache.setCache('token', token)

      // 获取 部门/角色 列表
      dispatch('getPageDepartmentListAction', null, { root: true })
      dispatch('getPageRoleListAction', null, { root: true })

      // 获取用户信息
      const userResult = await requestUserInfoById(id)
      const userInfo = userResult.data
      commit('changeUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)

      // 获取菜单信息
      const roleMenusResult = await requestUserMenusByRoleId(userInfo.role.id)
      const roleMenus = roleMenusResult.data
      commit('changeRoleMenus', roleMenus)
      localCache.setCache('roleMenus', roleMenus)

      // 页面跳转
      router.replace('/main')
    },
    // 初始化用户信息（刷新页面调用）
    setUpLoginAction({ commit, dispatch }) {
      const token = localCache.getCache('token')
      token && commit('changeToken', token)

      // 获取 部门/角色 列表
      dispatch('getPageDepartmentListAction', null, { root: true })
      dispatch('getPageRoleListAction', null, { root: true })

      const userInfo = localCache.getCache('userInfo')
      userInfo && commit('changeUserInfo', userInfo)
      
      const roleMenus = localCache.getCache('roleMenus')
      roleMenus && commit('changeRoleMenus', roleMenus)
    }
  }
}

export default LoginModule